<template>
  <div>
    <el-card class="box-card" style="width: 100%">
      您好，{{ username }}！欢迎使用本系统
    </el-card>
    <!-- 统计数量 -->
    <div class="cards" v-if="userType === 2 || userType === 9">
      <el-card class="box-card">
        <div class="card-avatar">
          <el-avatar :size="70" :src="stockUrl"></el-avatar>
          <div class="pro-card">
            <span>库存量</span>
            <h3>{{ statistics.stockCount }}</h3>
          </div>
        </div>
      </el-card>
      <el-card class="box-card">
        <div class="card-avatar">
          <el-avatar :size="70" :src="buyUrl"></el-avatar>
          <div class="pro-card">
            <span>采购订单</span>
            <h3>{{ statistics.buyOrderCount }}</h3>
          </div>
        </div>
      </el-card>
      <el-card class="box-card">
        <div class="card-avatar">
          <el-avatar :size="70" :src="saleUrl"></el-avatar>
          <div class="pro-card">
            <span>出库订单</span>
            <h3>{{ statistics.saleOrderCount }}</h3>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 统计echars -->
    <div class="cards" v-if="userType === 2 || userType === 9">
      <el-card class="box-card echars">
        <el-radio-group v-model="radio" @change="handleChange">
          <el-radio-button :label="1">今天</el-radio-button>
          <el-radio-button :label="7">近七天</el-radio-button>
          <el-radio-button :label="30">近一个月</el-radio-button>
        </el-radio-group>
        <br>
<!--        <div ref="chartContainer1" style="width: 600px; height: 300px;"></div>-->
        <div ref="chartContainer3" style="width: 600px; height: 300px;"></div>
      </el-card>
      <el-card class="box-card echars">
        <br><br>
        <div ref="chartContainer2" style="width: 600px; height: 300px;"></div>
      </el-card>
    </div>
    <!-- 系统公告 -->
    <div class="notice">
      <el-card class="box-card">
        <template #header>
          <span>系统公告</span>
        </template>
        <div class="block">
          <el-timeline>
            <el-timeline-item v-for="item in notes" :key="item.id" :timestamp="item.createTime" placement="top" size="large">
              <el-card style="width: 100%">
                <p style="width: 70vw">{{item.content}}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getSalesProportionOfGoods, getAllCount, getSaleStatistics } from '@/api/turnover'
import {getNoticeList} from "@/api/notice";

export default {
  name: 'LayoutPage',
  data () {
    return {
      stockUrl: require('@/assets/物资仓库-map.png'),
      buyUrl: require('@/assets/销售订单列表.png'),
      saleUrl: require('@/assets/新增采购订单.png'),
      // 默认是7天
      radio: 7,
      beginTime: null,
      endTime: null,
      // 销售额
      dateList: [],
      turnoversList: [],
      // 销售数
      salesList: [],
      salesDateList: [],
      // 商品占比
      saleCountAndGoodNameList: [],
      statistics: {
        stockCount: 0,
        buyOrderCount: 0,
        saleOrderCount: 0
      },
      notes: []
    }
  },
  async created () {
    // 页面加载时默认选择今天
    this.setLastWeek()
    const res = await getAllCount()
    this.statistics = res.data
  },
  mounted () {
    // this.getSalesProportionOfGoodsService()
    this.getTurnoverStatisticsList()
    this.getGoodsStatisticsList()
    this.getNotices()
  },
  methods: {
    //时间戳转日期字符串
    formatDateStr (timestamp) {
      let date = new Date(timestamp)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      // 天也需要0
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = date.getHours() + ':'
      let m = date.getMinutes() + ':'
      let s = date.getSeconds()
      return Y + M + D + h + m + s
    },
    async getNotices() {
      // 获取系统公告
      const res = await getNoticeList(1, 100)
      this.notes = res.data.list
    },
    echarts1 (e) {
      // 基于准备好的dom，初始化echarts实例
      const myChart = this.$echarts.init(e)
      // 绘制图表
      myChart.setOption({
        title: {
          text: '营业额',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            data: this.dateList
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            position: 'left',
            axisLabel: {
              formatter: '{value} ￥'
            }
          }
        ],
        series: [
          {
            type: 'line',
            smooth: true,
            data: this.turnoversList
          }
        ]
      })
    },
    echarts3 (e) {
      // 基于准备好的dom，初始化echarts实例
      const myChart = this.$echarts.init(e)
      // 绘制图表
      myChart.setOption({
        title: {
          text: '出库额',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            data: this.salesDateList
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '出库数量',
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            type: 'line',
            smooth: true,
            data: this.salesList
          }
        ]
      })
    },
    echarts2 (e) {
      // 基于准备好的dom，初始化echarts实例
      const myChart = this.$echarts.init(e)
      // 绘制图表
      myChart.setOption({
        title: {
          text: '销售比例',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: '20%'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: this.saleCountAndGoodNameList,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              // 重点
              label: {
                normal: {
                  formatter: '{b}:{c}: ({d}%)',
                  textStyle: {
                    fontWeight: 'normal',
                    fontSize: 15
                  }
                }
              }
            }
          }
        ]
      })
    },
    async getTurnoverStatisticsList () {
      // const res = await getTurnoverStatistics(this.beginTime, this.endTime)
      // this.dateList = res.data.dateList
      // this.turnoversList = res.data.turnoversList
      // this.echarts1(this.$refs.chartContainer1)
      await this.getSaleStatisticsService()
    },
    async getSaleStatisticsService () {
      const res = await getSaleStatistics(this.beginTime, this.endTime)
      this.salesDateList = res.data.dateList
      this.salesList = res.data.salesList
      this.echarts3(this.$refs.chartContainer3)
    },
    async getGoodsStatisticsList () {
      const res = await getSalesProportionOfGoods()
      this.saleCountAndGoodNameList = res.data
      this.saleCountAndGoodNameList = this.saleCountAndGoodNameList.map(item => ({
        value: item.saleCount,
        name: item.goodsName
      }))
      this.echarts2(this.$refs.chartContainer2)
    },
    // 时间
    handleChange () {
      if (this.radio === 1) {
        this.setToday()
      } else if (this.radio === 7) {
        this.setLastWeek()
      } else if (this.radio === 30) {
        this.setLastMonth()
      }
    },
    setToday () {
      const today = new Date()
      this.beginTime = this.formatDate(today)
      this.endTime = this.formatDate(today)
      this.getTurnoverStatisticsList()
    },
    setLastWeek () {
      const today = new Date()
      const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
      this.beginTime = this.formatDate(lastWeek)
      this.endTime = this.formatDate(today)
      this.getTurnoverStatisticsList()
    },
    setLastMonth () {
      const today = new Date()
      const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
      this.beginTime = this.formatDate(lastMonth)
      this.endTime = this.formatDate(today)
      this.getTurnoverStatisticsList()
    },
    formatDate (date) {
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()

      month = month < 10 ? `0${month}` : month
      day = day < 10 ? `0${day}` : day

      return `${year}-${month}-${day}`
    }
  },
  computed: {
    username () {
      return this.$store.getters.username
    },
    userType () {
      return Number(this.$store.getters.userType)
    }
  }

}
</script>

<style scoped>
.cards {
  display: flex;
  justify-content: space-between;
}

.box-card {
  width: 100%;
  margin: 5px 10px;
}

.box-card .pro-card {
  display: flex;
  flex-direction: column;
  line-height: 40px;
  align-items: center;
}

.pro-card > span {
  color: #6f6f6f;
}

.box-card ::v-deep .el-card__body {
  display: flex;
  justify-content: space-evenly;
}

.echars {
  width: 49.6%;
}

.echars ::v-deep .el-card__body {
  flex-direction: column;
  justify-content: flex-start;
}

.card-avatar {
  display: flex;
  width: 40%;
  justify-content: space-between;
}
</style>
